package com.microboom.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;

import javax.annotation.Nonnull;
import javax.sql.DataSource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.JdbcUtils;
import com.microboom.bean.command.RegisterCommand;
import com.microboom.bean.po.User;
import com.microboom.dao.UserDao;
import com.microboom.service.exception.PasswordIncorrectException;
import com.microboom.service.exception.RegisterUserException;
import com.microboom.service.exception.UserExistException;
import com.microboom.service.exception.UsernameNotExistException;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class AuthenticationService {

    @Autowired
    private UserDao userDao;

    public void login(@Nonnull String username, @Nonnull String password) {
        try {
            User user = userDao.select(username).orElseThrow(UsernameNotExistException::new);
            if (!user.getPassword().equals(password))
                throw new PasswordIncorrectException();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /*
     * Spring-tx 底层使用 Spring-aop 干了类似如下的事情：
     *
     * @Before: conn.setAutoCommit(false);
     * @AfterReturn: conn.commit();
     * @AfterThrowing: conn.rollback();
     */
    @Transactional
    public void register(@Nonnull RegisterCommand command) {
        try {
            // 判断该用户名是否已被使用
            Optional<User> optional = userDao.select(command.getUsername());
            if (optional.isPresent())
                throw new UserExistException();

            // 注册。将用户名密码存入数据库
            userDao.insert(command.getUsername(), command.getPassword());
        } catch (SQLException e) {
            log.warn("注册[{}]失败，其它错误原因：[{}]", command.getUsername(), e.getMessage(), e);
            throw new RegisterUserException();
        }
    }

    @Transactional
    public void demo(@Nonnull String username1, @Nonnull String username2) {
        log.info("准备删除[{}]和[{}]", username1, username2);

        try {
            User user1 = userDao.select(username1).orElseThrow(RuntimeException::new);
            userDao.delete(user1.getUid());
            log.info("删除[{}]成功", username1);

            User user2 = userDao.select(username2).orElseThrow(RuntimeException::new);
            userDao.delete(user2.getUid());
            log.info("删除[{}]成功", username2);
        } catch (SQLException e) {
            log.error("删除[{}]和[{}]发生内部错误: [{}]", username1, username2, e.getMessage(), e);
            throw new RuntimeException();
        }

    }
}
